/* 
 页面使用
 import { useList } from '@/hook/useList.js'
 const { list, getList } = useList('/user/list','get')
 getList()
 
 const { list:userList, getList:getUserList } = useList('/user/list','get',{
 	name:'123'
 })
 const { list: infoList, getList: getInfoList } = useList('/info/list','get')
 getUserList()
 getInfoList()
 */

// 导入接口请求封装
import { request } from '@/common/sju.request.js'

// 默认参数
const defaultConfig = {
	pageIndex: 1,
	pageSize: 10,
	data: {},
}

const useList = (url, method = 'get', data) => {
	const {
		pageIndex = defaultConfig.pageIndex,
		pageSize = defaultConfig.pageSize,
	} = defaultConfig
	
	if(data === undefined || data === '') {
		data = defaultConfig.data
	} else if (data && Object.prototype.toString.call(data) !== '[object Object]') {
		data = defaultConfig.data
	}
	
	const list = ref([])

	// 保存分页数据
	let pageInfo = reactive({
		pageIndex,
		pageSize,
		total: 0,
	})

	const getList = () => {
		const params = {
			...pageInfo,
			...data,
		}
		// 分页数据作为参数传递给接口调用函数即可
		return request(url,method,params).then((res) => {
			// 当前页不为1则是加载更多，需要拼接数据
			if (pageInfo.pageIndex === 1) {
				list.value = res.data.list
			} else {
				list.value = [...list.value, ...res.data.list]
			}
			pageInfo.total = res.data.total
			pageInfo.pageIndex += 1
			return res
		}).finally((info) => {
			// 不管成功还是失败，关闭下拉刷新的动画
			uni.stopPullDownRefresh()
			// 在最后再把前面返回的消息return出去，以便后续处理
			return info
		})
	}

	const getMoreList = () => {
		// 本次获取到空数组
		getList().then((res) => {
			if (!res.data.list.length) {
				uni.showToast({
					title: '已经加载全部',
					icon: 'none',
				})
			}
		})
	}

	// 初始化
	const init = () => {
		pageInfo.pageIndex = 1
		getList()
	}

	// 下拉加载
	onPullDownRefresh(init)
	// 上拉加载
	onReachBottom(getMoreList)
	
	return {
		init,
		list,
		getList,
		getMoreList
	}
}

export { useList }
